//
//  GLFormViewController.m
//  KTools
//
//  Created by zhiyong.kuang on 2017/9/28.
//  Copyright © 2017年 zhiyong.kuang. All rights reserved.
//

#import "UIViewController+GLForm.h"
#import "GLFormSection.h"
#import "GLFormRow.h"
#import "GLForm.h"
#import "GLPickerView.h"
#import "GLCustomCell.h"
#import <objc/runtime.h>
#import "Masonry.h"

static char GLTableViewKey;
static char GLTableFormKey;


@implementation UIViewController (GLForm)


#pragma mark - UIInit

-(void)gl_registerForm:(GLForm*)form{
    self.gl_form = form;
    [self gl_UIInit];
}

-(void)gl_UIInit{
    
    [self.view addSubview:self.gl_tableView];
    [self.gl_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.view);
        if (self.gl_form.showCorner) {
            make.left.equalTo(self.view).offset(10);
            make.right.equalTo(self.view).offset(-10);
        }else{
            make.right.left.equalTo(self.view);
        }
        
    }];
    
    
    if (self.gl_form.showCorner) {
        self.gl_tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, -5);
    }

    self.view.backgroundColor = [UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:1];

    self.gl_tableView.backgroundColor = self.view.backgroundColor;

}



#pragma mark- api



- (void)gl_reloadFormRow:(GLFormRow*)row{
    NSIndexPath* indexPath = [self.gl_form indexPathForFormRow:row];
    if (!indexPath) {
        return;
    }
    [self.gl_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)gl_reloadFormSection:(GLFormSection*)section{
    NSInteger index = [self.gl_form indexformSection:section];
    if (index != NSNotFound) {
        [self gl_reloadSection:index];
    }
}

- (void)gl_reloadSection:(NSUInteger)section{
    [self gl_reloadSections:[NSIndexSet indexSetWithIndex:section]];
}
- (void)gl_reloadSections:(NSIndexSet *)sections{
    [self.gl_tableView reloadSections:sections withRowAnimation:UITableViewRowAnimationNone];
}
- (void)gl_reloadForm{
    [self.gl_tableView reloadData];
}

#pragma mark - tableviewDataSource && tableviewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.gl_form.sectioins.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    GLFormSection* formsection = self.gl_form.sectioins[section];
    return formsection.rows.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GLFormSection* formsection = self.gl_form.sectioins[indexPath.section];
    
    GLFormRow* row = [formsection.rows objectAtIndex:indexPath.row];
//    row.form = self;
    
    GLFormBaseCell* cell = [row cellForForm:self.gl_form tableView:tableView];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GLFormSection* formsection = self.gl_form.sectioins[indexPath.section];
    GLFormRow* row = [formsection.rows objectAtIndex:indexPath.row];
    
    if (self.gl_form.formClicked) {
        self.gl_form.formClicked(row,tableView,NO, row.tag);
    }
    [self formRowClicked:row];
    if (row.action == GLFormRowActionPicker) {
        [GLPickerView showDatas:row.options convert:nil competion:^(GLPickerEvent event, id value) {
            if (event == GLPickerEventSure) {
                [row setRowValue:value];
            }
        }];
    }
    else if (row.action == GLFormRowActionPushViewController) {
        if (!self.navigationController){
            NSLog(@"GLFormRowActionPush navigationController can't been nil");
        }
        if (self.navigationController && row.pushViewController) {
            if ([row.pushViewController isKindOfClass:[NSString class]]) {
                Class pushClass = NSClassFromString(row.pushViewController);
                if (pushClass) {
                    [self.navigationController pushViewController:[[pushClass alloc]init] animated:YES];
                }
                else{
                    NSLog(@"error pushViewController is nil");
                }
            }
        }
    }
    else if (row.action == GLFormRowActionPushInput){
        if (!self.navigationController){
            NSLog(@"GLFormRowActionPush navigationController can't been nil");
        }
        GLFormOptionViewController* ctl = [[GLFormOptionViewController alloc]init];
        ctl.actionType = row.action;
        ctl.formRow = row;
        [self.navigationController pushViewController:ctl animated:YES];
    }
    else if (row.action == GLFormRowActionPushOption) {
        if (!self.navigationController){
            NSLog(@"GLFormRowActionPush navigationController can't been nil");
        }
        GLFormOptionViewController* ctl = [[GLFormOptionViewController alloc]init];
        ctl.actionType = row.action;
        ctl.options = row.options;
        ctl.formRow = row;
        [self.navigationController pushViewController:ctl animated:YES];
    }
//    else if (row.action == GLFormRowActionPushSwitch) {
//        if (!self.navigationController){
//            NSLog(@"GLFormRowActionPush navigationController can't been nil");
//        }
//        GLFormOptionViewController* ctl = [[GLFormOptionViewController alloc]init];
//        ctl.actionType = row.action;
//        ctl.formRow = row;
//        [self.navigationController pushViewController:ctl animated:YES];
//    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GLFormSection* formsection = self.gl_form.sectioins[indexPath.section];
    GLFormRow* row = [formsection.rows objectAtIndex:indexPath.row];
    
    return row.rowHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    GLFormSection* formsection = self.gl_form.sectioins[section];

    return formsection.HeaderHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    GLFormSection* formsection = self.gl_form.sectioins[section];
    if (section == self.gl_form.sectioins.count -1 && formsection.footerHeight < 1) {
        return 15.0f;
    }
    return formsection.footerHeight;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    GLFormSection* formsection = self.gl_form.sectioins[section];
    NSString* title = formsection.tag;
    if (title) {
        return title;
    }

    return nil;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    GLFormSection* formsection = self.gl_form.sectioins[section];
    return formsection.headerView;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    GLFormSection* formsection = self.gl_form.sectioins[section];
    return formsection.footerView;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.gl_form.showCorner) {
        [self resetCellAll:cell];

        GLFormSection* formsection = self.gl_form.sectioins[indexPath.section];
        if (formsection.rows.count == 1) {
            [self clipCellAll:cell];
        }else{
            if (indexPath.row == 0) {
                [self clipCellTop:cell];
            }
            else if (indexPath.row == formsection.rows.count-1){
                [self clipCellBottom:cell];

            }
        }
    }

    if ([cell respondsToSelector:@selector(resetSeparatorInset)]) {
        [(GLFormBaseCell*)cell resetSeparatorInset];
    }

}

- (void)clipCellTop:(UIView *)view
{
    //将要显示cell的时候对其进行裁剪
    UIBezierPath *bezierpath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 1.0/[UIScreen mainScreen].scale, view.bounds.size.width, view.bounds.size.height) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = bezierpath.CGPath;
    view.layer.mask = maskLayer;
}

- (void)clipCellBottom:(UIView *)view
{
    //将要显示cell的时候对其进行裁剪
    UIBezierPath *bezierpath = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, view.bounds.size.width, view.bounds.size.height-1.0/[UIScreen mainScreen].scale) byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = bezierpath.CGPath;
    view.layer.mask = maskLayer;
    
}

- (void)clipCellAll:(UIView *)view
{
    CGFloat lineWidth = 1.0/[UIScreen mainScreen].scale;
    CGRect frame = CGRectMake(0, lineWidth, view.bounds.size.width, view.bounds.size.height-2*lineWidth);
    UIBezierPath *bezierpath = [UIBezierPath bezierPathWithRoundedRect:frame byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = bezierpath.CGPath;
    view.layer.mask = maskLayer;
}

- (void)resetCellAll:(UIView *)view
{
    UIBezierPath *bezierpath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(0, 0)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = bezierpath.CGPath;
    view.layer.mask = maskLayer;
}

-(void)formRowClicked:(GLFormRow*)row{
    
}

#pragma mark- setter and getter
-(UITableView*)gl_tableView{
    
    UITableView* tabV = objc_getAssociatedObject(self, &GLTableViewKey);
    
    if (!tabV) {
        tabV = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tabV.dataSource = self;
        tabV.delegate = self;
        
        objc_setAssociatedObject(self, &GLTableViewKey, tabV, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return tabV;
}


#pragma mark- setter and getter
-(GLForm*)gl_form{
    return  objc_getAssociatedObject(self, &GLTableFormKey);
}


-(void)setGl_form:(GLForm *)form{

    if (self.gl_form != form) {
        objc_setAssociatedObject(self, &GLTableFormKey, form, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        if(form.formHeaderView){
            self.gl_tableView.tableHeaderView = form.formHeaderView;
        }else{
            UIView* v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.001)];
            self.gl_tableView.tableHeaderView = v;
        }
        if(form.formFooterView){
            self.gl_tableView.tableFooterView = form.formFooterView;
        }else{
            UIView* v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0.001)];
            self.gl_tableView.tableFooterView = v;
        }
        
        
        if (self.gl_tableView) {
            [self.gl_tableView reloadData];
        }
    }
}

@end

#pragma mark- GLFormOptionViewController
@interface GLFormOptionViewController()
@property(nonatomic,assign)NSInteger selectIndex;
@end

@implementation GLFormOptionViewController
-(void)viewDidLoad{
    [super viewDidLoad];
    _selectIndex = 0;
    [self configForm];
}

-(void)configForm{
    GLForm* form = [GLForm formWithTag:@"form"];
    switch (self.actionType) {
        case GLFormRowActionPushOption:
        {
            
            NSArray* array = (NSArray*)self.options;
            for(NSString* title in array){
                if (self.formRow && [self.formRow.value isEqualToString:title]) {
                    _selectIndex = [array indexOfObject:title];
                }
            }
            
            GLFormSection* section = [GLFormSection formSectionWithTag:@""];
            for(NSString* title in array){
                GLFormRow* row1 = [GLFormRow formRowByComponentKeys:@[GLCustomCellText,GLCustomCellRadio] withTag:@"option"];
                [row1 addConfigValue:title componentKey:GLCustomCellText forKeyPath:nil];
                row1.valueKey = GLCustomCellRadio;
                if (_selectIndex == [array indexOfObject:title]) {
                    row1.value = [NSNumber numberWithBool:YES];
                }else{
                    row1.value = [NSNumber numberWithBool:NO];
                }
                
                [section addFormRow:row1];
            }
            [form addFormSection:section];
            break;
        }
//        case GLFormRowActionPushSwitch:
//        {
//
//            BOOL yesOrNot = [self.formRow.value boolValue];
//            GLFormSection* section = [GLFormSection formSectionWithTag:@""];
//            GLFormRow* row1 = [GLFormRow formRowByComponentKeys:@[GLCustomCellText,GLCustomCellSwitch] withTag:@"switch"];
//            [row1 addConfigValue:self.title componentKey:GLCustomCellText forKeyPath:nil];
//            row1.value = [NSNumber numberWithBool:yesOrNot];
//
//            [section addFormRow:row1];
//            [form addFormSection:section];
//            break;
//        }
        case GLFormRowActionPushInput:
        {
            GLFormSection* section = [GLFormSection formSectionWithTag:@""];
            GLFormRow* row1 = [GLFormRow formRowByComponentKeys:@[GLCustomCellInput] withTag:@"input"];
            row1.valueKey = GLCustomCellInput;
            row1.value = self.formRow.value;
           
            [section addFormRow:row1];
            [form addFormSection:section];
            break;
        }
        default:
            break;
    }
    
    __weak typeof(self) weakSelf = self;
    form.formClicked = ^(GLFormRow *row, id sender, BOOL isSub, NSString *subTag) {
        if (isSub) {
            return ;
        }
        if (weakSelf.actionType == GLFormRowActionPushOption) {
            
            NSArray* rows = [weakSelf.gl_form formRowsWithTag:@"option"];
            for (GLFormRow* aRow in rows) {
                if (aRow == row) {
                    weakSelf.selectIndex = [weakSelf.gl_form indexPathForFormRow:row].row;
                    [aRow setRowValue:[NSNumber numberWithBool:YES]];
                    
                }else{
                    [aRow setRowValue:[NSNumber numberWithBool:NO]];
                }
            }
        }
    };
    
    [self gl_registerForm:form];
    
}

-(void)dealloc{
    if (self.formRow) {
        switch (self.actionType) {
            case GLFormRowActionPushOption:
            {
                
                NSString* value = self.options[_selectIndex];
                [self.formRow setRowValue:value?value:@""];
                break;
            }
//            case GLFormRowActionPushSwitch:
//            {
//
//                GLFormRow* row1 = [GLFormRow formRowByComponentKeys:@[GLCustomCellText,GLCustomCellSwitch] withTag:@"switch"];
//
//                break;
//            }
            case GLFormRowActionPushInput:
            {
                NSDictionary* values = [self.gl_form formValues];
                NSString* value = values[@"input"];
                [self.formRow setRowValue:value?value:@""];
                
                break;
            }
            default:
                break;
        }
    }
}

@end
